<?php
namespace App\Listeners;

use App\Events\In\NormalBuyingFinished;
use App\Events\In\StudentAppointmentStatusChanged;
use App\Events\Out\EventGiftLessonShareCreated;
use App\Facades\KafkaBridge;
use App\Models\GiftLessonShare;
use App\Models\GiftLessonStudent;
use Carbon\Carbon;

class OnStudentAppointmentStatusChanged
{
    public function handle(StudentAppointmentStatusChanged $event)
    {
        $studentId = $event->studentId;
        if (intval($event->toStatus) !== 3) return;

        $student = GiftLessonStudent::find($studentId);
        if (empty($student)) return;
        if ($student->getStatus() != GiftLessonStudent::STATUS_UNLOCK) return;
        $student->increaseLessonCount();

        if ($student->getLessonCount() - $student->getLastActiveLessonCount() >= GiftLessonStudent::SHARE_LESSON_COUNT) {
            $shareCount = GiftLessonShare::query()->count();
            if ($shareCount >= GiftLessonshare::LESSON_SHARES_MAX_LIMIT) {
                return;
            }
            $student->save();
            $student->setLastActiveLessonCount($student->getLessonCount());
            $student->increaseShareCount();

            $share = new GiftLessonShare();
            $share->setStudentId($studentId);
            $share->setShareCode(uniqid(GiftLessonShare::SHARE_CODE_PREFIX));
            $share->setExpiredAt(Carbon::now()->addDays(GiftLessonShare::EXPIRE_DAYS));
            $share->save();

            $event = new EventGiftLessonShareCreated();
            $event->studentId = $studentId;
            $event->shareCode = $share->getShareCode();
            $event->expiredAt = $share->getExpiredAt()->getTimestamp();

            KafkaBridge::push($event);
        }

        $student->save();
    }
}